package org.oims.simpleserver.endpoint;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.oims.simpleserver.emiter.EventEmitter;
import org.oims.simpleserver.entities.event.EndpointClosed;
import org.oims.simpleserver.entities.event.EndpointToken;
import org.oims.simpleserver.exceptions.IllegalOperationException;
import org.oims.simpleserver.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint(value = "/wss/topic")
@Component
public class WebSocketEndpoint implements Endpoint {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    private EventEmitter eventEmitter;
    private Session session;
    private String id;

    @OnOpen
    public void onOpen(Session session) {
        try {
            this.session = session;
            this.eventEmitter = SpringUtils.getBean(EventEmitter.class);
            logger.info("Websocket endpoint (hash code: '" + this.hashCode() + "') is opened");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(){
        close();
    }

    @OnError
    public void onError(Session session, Throwable throwErr){
        logger.error("Websocket endpoint (hash code:'" + this.hashCode() + "') has error: " + throwErr.getMessage());
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String msgText) {
        try {
            JSONObject json = JSON.parseObject(msgText);
            String name = json.getString("name");
            //根据token验证浏览器身份
            if(StringUtils.equals(name, "endpoint-token")){
                String token = json.getString("token");
                eventEmitter.emit(name, new EndpointToken(token, this));
            }
        }catch (IllegalOperationException e){
            e.printStackTrace();
        }

    }

    @Override
    public void sendMsg(String msg) throws IOException {
        this.session.getBasicRemote().sendText(msg);
    }

    private void close(){
        if(this.id != null){
            eventEmitter.emit("endpoint-closed", new EndpointClosed(this.id, this));
        }
        logger.info("Websocket endpoint (hash code:'" + this.hashCode() + "') is closed");
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void setId(String id) {
        this.id = id;
    }
}
